package Admin;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import javax.swing.JDesktopPane;
import javax.swing.JTextArea;

import com.example.finalproj.ChatData;

public class ServerThread extends Thread{
	
	Socket soc;
	String myid="";
	String toid="";
	String grade="0";
	boolean flag=true;
	
	Connection conn;
	PreparedStatement pst;
	ResultSet rs;
	String sql;
	
	Chat_Internal_Frame my_cif;
	
	
	HashMap<String, ServerThread> user;
	JTextArea ta_log;
	JDesktopPane main_jdp;
	HashMap<String, Chat_Internal_Frame> design;
	
	ObjectInputStream ois;
	ObjectOutputStream oos;
	
	public ServerThread() {
		// TODO Auto-generated constructor stub
	}
	public ServerThread(HashMap<String, ServerThread> user, Socket soc, JTextArea ta_log, JDesktopPane main_jdp, HashMap<String, Chat_Internal_Frame> design)
	{
		this.design = design;
		this.main_jdp = main_jdp;
		this.user = user;
		this.soc = soc;
		this.ta_log = ta_log;
		this.ta_log.append("익명접속 : "+soc.getInetAddress().getHostAddress()+"\n");
		start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try
		{
			oos = new ObjectOutputStream(soc.getOutputStream());
			ois = new ObjectInputStream(soc.getInputStream());
			
			while(flag)
			{
				ChatData cd = (ChatData)ois.readObject();
				switch(cd.getAction())
				{
				case 1: //login
					myid = cd.getFromid();
					toid = cd.getToid();
					user.put(myid, this);
					ta_log.append(myid+" 님 로그인\n");
					sql = "select grade from member where mid=?";
					conn = new MySqlDB().getConn();
					pst = conn.prepareStatement(sql);
					pst.setString(1, myid);
					rs = pst.executeQuery();
					boolean have = false;
					if(rs.next())
					{
						grade = rs.getString("grade");
						if(grade.equals("3")) // 일반 사용자라면
						{
							Iterator<String> de = design.keySet().iterator(); //디자이너 아이디중
							while(de.hasNext())
							{
								if(de.next().equals(toid)) // 상담 디자이너가 있는가? 있다면
								{
									my_cif = design.get(toid);
									have = true;
									break;
								}
							}
							if(!have) // 상담 디자이너가 없을때 프래임 생성. (디자이너 아이디로)
							{
								Chat_Internal_Frame ciframe = new Chat_Internal_Frame(user, ta_log, toid);
								design.put(toid, ciframe);
								main_jdp.add(ciframe);
								ciframe.setVisible(true);
								my_cif = ciframe;
							}
						}
						else // 디자이너라면
						{
							Iterator<String> de = design.keySet().iterator(); // 디자이너중
							while(de.hasNext())
							{
								if(de.next().equals(myid)) // 내가 있는가? 있다면
								{
									my_cif = design.get(myid);
									Iterator<String> tal = my_cif.talk.keySet().iterator();
									if(tal.hasNext())
									{
										if(tal.next().equals(toid))
										{
											String allchat = my_cif.talk.get(toid).ta_chatting.getText();
											ChatData c = new ChatData();
											c.setAction(92);
											c.setMsg(allchat);
											oos.writeObject(c);
										}
									}
									have = true;
									break;
								}
							}
//							if(!have) // 내가 디자이너 이고, 상담창이 없으므로 상담신청이 없다.
//							{
//								Chat_Internal_Frame ciframe = new Chat_Internal_Frame(user, ta_log, myid);
//								design.put(myid, ciframe);
//								main_jdp.add(ciframe);
//								ciframe.setVisible(true);
//								my_cif = ciframe;
//							}
						}
					}
					break;
				case 2: //msg
					cd.setGrade(grade);
					my_cif.receiveMsg(cd);
					
					ta_log.append(cd.getFromid() + " -> " + toid + " : " + cd.getMsg()+"\n");
					ta_log.setCaretPosition(ta_log.getText().length());
					
					user.get(myid).oos.writeObject(cd);
					Iterator<String> use = user.keySet().iterator();
					while(use.hasNext())
					{
						if(use.next().equals(toid))
						{
							user.get(toid).oos.writeObject(cd);
							break;
						}
					}
					break;
				case 3: //logout
					cd.setGrade(grade);
					ta_log.append(myid+" 님 로그아웃\n");
					my_cif.receiveMsg(cd);
					user.get(myid).oos.writeObject(cd);
					flag = false;
					break;
				case 91: // 디자이너임을 알리고 로그인 했을때
					myid = cd.getFromid();
					user.put(myid, this);
					String sql = "select grade from member where mid=?";
					Connection conn = new MySqlDB().getConn();
					PreparedStatement pst = conn.prepareStatement(sql);
					pst.setString(1, myid);
					ResultSet rs = pst.executeQuery();
					rs.next();
					grade = rs.getString("grade");
					String talk_user="";
					if(!grade.equals("3"))
					{
						Iterator<String> it = design.keySet().iterator();
						while(it.hasNext())
						{
							if(it.next().equals(myid))
							{
								Iterator<String> italk = design.get(myid).talk.keySet().iterator();
								while(italk.hasNext())
								{
									talk_user = talk_user +"/"+italk.next();
								}
								break;
							}
						}
						cd = new ChatData();
						cd.setAction(91);
						cd.setMsg(talk_user);
						oos.writeObject(cd);
						flag = false;
					}
					break;
				}
			}
			Iterator<String> iter = user.keySet().iterator();
			while(iter.hasNext())
			{
				if(iter.next().equals(myid))
				{
					user.remove(myid);
					break;
				}
			}
			
			ois.close();
			oos.close();
			soc.close();
			soc=null;
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	
}
